package repository

import (
	"context"
	"github.com/example/video_backend/internal/model"
	"gorm.io/gorm"
)

// LikeRepository 点赞仓库接口
type LikeRepository interface {
	Create(ctx context.Context, like *model.Like) error
	Delete(ctx context.Context, userID, videoID uint) error
	IsLiked(ctx context.Context, userID, videoID uint) (bool, error)
	GetUserLikes(ctx context.Context, userID uint, page, pageSize int) ([]*model.Like, int64, error)
}

// likeRepository 实现LikeRepository接口
type likeRepository struct {
	db *gorm.DB
}

// NewLikeRepository 创建点赞仓库实例
func NewLikeRepository(db *gorm.DB) LikeRepository {
	return &likeRepository{db: db}
}

// Create 创建点赞
func (r *likeRepository) Create(ctx context.Context, like *model.Like) error {
	return r.db.WithContext(ctx).Create(like).Error
}

// Delete 删除点赞
func (r *likeRepository) Delete(ctx context.Context, userID, videoID uint) error {
	return r.db.WithContext(ctx).Where("user_id = ? AND video_id = ?", userID, videoID).Delete(&model.Like{}).Error
}

// IsLiked 检查用户是否已点赞视频
func (r *likeRepository) IsLiked(ctx context.Context, userID, videoID uint) (bool, error) {
	var count int64
	err := r.db.WithContext(ctx).Model(&model.Like{}).Where("user_id = ? AND video_id = ?", userID, videoID).Count(&count).Error
	if err != nil {
		return false, err
	}
	return count > 0, nil
}

// GetUserLikes 获取用户的点赞列表
func (r *likeRepository) GetUserLikes(ctx context.Context, userID uint, page, pageSize int) ([]*model.Like, int64, error) {
	var likes []*model.Like
	var total int64

	// 计算偏移量
	offset := (page - 1) * pageSize

	// 构建查询
	query := r.db.WithContext(ctx).Where("user_id = ?", userID)

	// 查询总数
	query.Model(&model.Like{}).Count(&total)

	// 查询分页数据
	err := query.Offset(offset).Limit(pageSize).Order("created_at DESC").Find(&likes).Error
	if err != nil {
		return nil, 0, err
	}

	return likes, total, nil
}
